<?php

namespace Admin\Controller;

use User\Api\UserApi;

use Think\Model;
use Org\Util\Rest;
use Org\BMap; 

/**
 * 团购控制器
 * @author zhangwei
 * 2015-05-22
 */
class GroupPurchaseController extends AdminController {

    /**
     * 团购列表
     * @author James
     * 2015-06-19
     */
    public function index() {
        $title = I('title');
        $sql = "select a.* from gr_grouppurchase a where a.status = 1 and a.gpname like '%".$title."%'";
        $model = new \Think\Model();
        $list = $model->query($sql);
        int_to_string($list);
         
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }
    
    /**
     * 团购商品列表
     * @author James
     * 2015-06-19
     */
    public function proindex() {
        $title = I('title');
        $sql = "select a.*,
               (select b.gpName from gr_grouppurchase b where a.gpId = b.id) gpName,
               (select count(1) from gr_gp_order_goods b where a.id = b.pid) sale_Cnt
               from gr_grouppurchase_pro a 
               where a.status = 1 and a.proName like '%".$title."%'";
        $model = new \Think\Model();
        $list = $model->query($sql);
        int_to_string($list);
         
        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 新增团购
     * @author zhangwei
     * 2015-05-22
     */
    public function add($gpName = "", $begindate = "", $enddate = "") {
        if (IS_POST) {
            // 上传文件 
            $setting = array(
                'mimes' => '', //允许上传的文件MiMe类型
                'maxSize' => 2 * 1024 * 1024, //上传的文件大小限制 (0-不做限制)
                'exts' => 'jpg,gif,png,jpeg', //允许上传的文件后缀
            );

            /* 调用文件上传组件上传文件 */
            /*             * 修改开始* */
            $pic_driver = C('PICTURE_UPLOAD_DRIVER');
            $upload = new \Think\Upload($setting, C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG"));
            $info = $upload->upload();
            
            if (!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } else {// 上传成功
                $data = array('gpName' => $gpName, 'fileUrl' => $info["photo"]["url"], 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate), 'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME);
                $id = M('grouppurchase')->add($data);
                if (!$id) {
                    $this->error("添加失败！");
                } else {
                    $this->success('添加成功！', U('index'));
                }
            }
        } else {
            $this->display();
        }
    }
    
    /**
     * 新增团购商品
     * @author James
     * 2015-06-19
     */
    public function proadd($gpId = "", $proName = "", $gpprice = "", $grprice = "", $maxCnt = "", $minCnt = "", $gpsaleCnt = "", $picarry = "", $intro = "", $content = "") {
        if (IS_POST) {
            
            $saleCnt_array = I('saleCnt');
            $price_array = I('price');
            
            for ($i = 0; $i < count($saleCnt_array); $i++) {
                if ($saleCnt_array[$i] == ""  || $price_array[$i] == "") {
                    $this->error("团购分级内容不能为空");
                }
            }
            
            $ProductData = array('gpId' => $gpId, 'proName' => $proName, 'price' => $gpprice, 'grprice' => $grprice, 'maxCnt' => $maxCnt, 'minCnt' => $minCnt, 'saleCnt' => $gpsaleCnt, 'picarry' => $picarry, 'intro' => $intro, 'content' => $content, 'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME);
            $Product = D('grouppurchase_pro');
          
            $data = $Product->create($ProductData);
            if ($data) {
                if (!($pid = $Product->add())) {
                    $this->error("商品添加失败！");
                } else {
                    for ($i = 0; $i < count($saleCnt_array); $i++) {
                        $dataList[] = array('proId' => $pid, 'gpId' => $gpId, 'price' => $price_array[$i], 'saleCnt' => $saleCnt_array[$i], 'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME);
                    }
                    D('grouppurchase_grade')->addAll($dataList);
                    $this->success('商品添加成功！', U('proindex'));
                }
            } else {
                $this->error($Product->getError());
            }
        } else {
            $list = M('grouppurchase')->where('status=1')->order('createdate desc')->select();
            $data['list'] = $list;
            $this->data = $data;
            $this->display();
        }
    }
    
    /**
     * 团购修改
     * @author wangyuanlin
     * 2015-06-19
     */
    public function edit($gpName = "", $begindate = "", $enddate = "") {
        $id = I('id');
        if (IS_POST) {
            
            // 上传文件 
            $setting = array(
                'mimes' => '', //允许上传的文件MiMe类型
                'maxSize' => 2 * 1024 * 1024, //上传的文件大小限制 (0-不做限制)
                'exts' => 'jpg,gif,png,jpeg', //允许上传的文件后缀
            );

            /* 调用文件上传组件上传文件 */
            /*             * 修改开始* */
            $pic_driver = C('PICTURE_UPLOAD_DRIVER');
            $upload = new \Think\Upload($setting, C('PICTURE_UPLOAD_DRIVER'), C("UPLOAD_{$pic_driver}_CONFIG"));
            $info = $upload->upload();
            
            $syncStatus = M('grouppurchase')->where(array('id' => $id))->getField('syncStatus');
            
            if($info){
                if($syncStatus == 0){
                    //已经上推过了
                    $data = array('gpName' => $gpName, 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate), 'fileUrl' => $info["photo"]["url"], 'lastupdate' => NOW_TIME, 'syncStatus' => 2);
                }else{
                    //还没上推过了
                    $data = array('gpName' => $gpName, 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate), 'fileUrl' => $info["photo"]["url"], 'lastupdate' => NOW_TIME);
                }
            }else{
                if($syncStatus == 0){
                    //已经上推过了
                    $data = array('gpName' => $gpName, 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate), 'lastupdate' => NOW_TIME, 'syncStatus' => 2);
                }else{
                    //还没上推过了
                    $data = array('gpName' => $gpName, 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate), 'lastupdate' => NOW_TIME);
                }
            }
            
            if (!M('grouppurchase')->where(array('id' => $id))->save($data)) {
                $this->error("修改失败！");
            } else {
                $this->success('修改成功！', U('index'));
            }
        } else {
            $data = M('grouppurchase')->where(array('id' => $id))->find();
            $this->data = $data;
            $this->display();
        }
    }
    
    /**
     * 团购商品修改
     * @author wangyuanlin
     * 2015-06-19
     */
    public function proedit($gpId = "", $proName = "", $gpprice = "", $grprice = "", $maxCnt = "", $minCnt = "", $gpsaleCnt = "", $picarry = "", $intro = "", $content = "") {
        $id = I('id');
        if (IS_POST) {
            $saleCnt_array = I('newsaleCnt');
            $price_array = I('newprice');
            
            if ($saleCnt_array) {
                for ($i = 0; $i < count($saleCnt_array); $i++) {
                    if ($saleCnt_array[$i] == "" || $price_array[$i] == "") {
                        $this->error("团购分级信息内容不能为空");
                    }
                }
            }
            
            $syncStatus = M('grouppurchase_pro')->where(array('id' => $id))->getField('syncStatus');
            
            if($syncStatus == 0){
                //已经上推过了
                $ProductData = array('gpId' => $gpId, 'proName' => $proName, 'price' => $gpprice, 'grprice' => $grprice, 'maxCnt' => $maxCnt, 'minCnt' => $minCnt, 'saleCnt' => $gpsaleCnt, 'picarry' => $picarry, 'intro' => $intro, 'content' => $content, 'lastupdate' => NOW_TIME, 'syncStatus' => 2);
            }else{
                //还没上推过了
                $ProductData = array('gpId' => $gpId, 'proName' => $proName, 'price' => $gpprice, 'grprice' => $grprice, 'maxCnt' => $maxCnt, 'minCnt' => $minCnt, 'saleCnt' => $gpsaleCnt, 'picarry' => $picarry, 'intro' => $intro, 'content' => $content, 'lastupdate' => NOW_TIME);
            }
            
            $Product = D('grouppurchase_pro');
            if ($Product->create($ProductData) && $Product->where(array('id' => $id))->save()) {
                if ($saleCnt_array) {
                    for ($i = 0; $i < count($saleCnt_array); $i++) {
                        $dataList[] = array('proId' => $id, 'gpId' => $gpId, 'price' => $price_array[$i], 'saleCnt' => $saleCnt_array[$i], 'lastupdate' => NOW_TIME);
                    }
                    D('grouppurchase_grade')->addAll($dataList);
                }
                $this->success('修改成功！', U('proindex'));
            } else {
                $this->error($Product->getError());
            }
        } else {
            $data['Product'] = M('grouppurchase_pro')->where(array('id' => $id))->find();
            $list = M('grouppurchase')->where('status=1')->order('createdate desc')->select();
            $data['list'] = $list;

            $spclist = M('grouppurchase_grade')->where(array('gpId' => $data['Product']['gpId'],'proId' => $id, 'status' => 1))->select();
            $data['spclist'] = $spclist;

            $this->Product = $data['Product'];
       
            $this->data = $data;
            $this->display();
        }
    }

    /**
     * 团购订单
     * @author zhangwei
     * 2015-05-22
     */
    public function order() {
        $Model = new Model();
        
        $id = I('id');          //订单编号
        $aid = I('aid');        //区域
        $dayId = I('dayId');    //当天订单序号
        $status = I('status');  //订单状态
        $b_date = I('b_date');  //开始时间
        $e_date = I('e_date');  //结束时间
        
        //拼接SQL语句
        $sql = "select a.*,
            (select b.gpName from gr_grouppurchase b where a.gpId = b.id) gpName
            from gr_gp_order a where 1=1 ";
        
        if ($id) {
            $sql .= " and a.orderid like '%".$id."%'";
        }
        if ($dayId) {
            $sql .= " and a.serialNo = '".$dayId."'";
        }
        if ($aid) {
            $sql .= " and a.areaId = '".$aid."'";
        }
        if ($status) {
            $sql .= " and a.status = '".$status."'";
        }
        if ($b_date) {
            $sql .= " and date_format(a.createDate,'%Y-%m-%d') >= '".$b_date."' ";
        }
        if ($e_date) {
            $sql .= " and date_format(a.createDate,'%Y-%m-%d') <= '".$e_date."' ";
        }
        $sql .= " order by createDate,orderid desc";
        $list = $Model->query($sql);
        
        int_to_string_order($list);
        
        $areaList = M("area")->where(array('status'=>1))->select();
        $data['areaList'] = $areaList;
        
        $this->assign('data', $data);
        $this->assign('_list', $list);
        $this->assign('_status', $status);
        $this->assign('_aid', $aid);
        
        $this->display();
    }
    
    /**
     * 订单详情
     * @author zhangwei
     * 2015-06-18
     */
    public function orderDetails($orderid = null){
        $map['orderid'] = $orderid;  
        $orderlist = D('gp_order')->where($map)->select();
        int_to_string_order($orderlist); 
        $order=$orderlist[0];            
        $order['order_goods'] = M('gp_order_goods')->where(array('orderid' => $orderid))->select();
        $this->order = $order;
        $this->display();
    }
    /**
     * 撤销订单
     * @author zhangwei
     * 2015-06-18
     */
    public function canelOrder($orderid = null){
        
        $syncStatus = M('gp_order')->where(array('orderid' => $orderid))->getField('syncStatus');
        
        if($syncStatus == 0){
            //已经上推过了
            $order = array('status' => -2,'syncStatus' => 2);
        }else{
            //还没上推过了
            $order = array('status' => -2);
        }
        
        $orderTable = D('gp_order');
        if ($orderTable->where(array('orderid' => $orderid))->save($order)) {
            $this->success("订单撤销成功!");
        } else {
            $this->error("数据没有发生变化，撤销失败！");
        }
    }
    
    /**
     * 下拉
     * @author zhangwei
     * 2015-05-21
     */
    public function pull() {
        $sync = new Sync();

        $reuslt = $sync->pull("Order");
        $reuslt = $sync->pull("OrderGoods");
        $this->success('订单数据下拉成功！', U('index'), true);
    }
    
     /**
     * 删除品类
     * @author wangyuanlin
     * 2015-06-19
     */
    public function del($id = 0) {
        if ($id) {
            $grouppurchase = M("grouppurchase");
            
            $data = array('status'=>-1,'syncStatus' => 3);
            $result = $grouppurchase-> where(array('id'=>$id))->setField($data);
            
            if($result){
                $this->success('删除成功！', U('index'));
            }else{
                $this->error("删除失败！");
            }
            
        }
    }
    
    
    /**
     * 删除品类
     * @author wangyuanlin
     * 2015-06-19
     */
    public function prodel($id = 0) {
        if ($id) {
            $grouppurchase = M("grouppurchase_pro");
            
            $data = array('status'=>-1,'syncStatus' => 3);
            $result = $grouppurchase-> where(array('id'=>$id))->setField($data);
            
            if($result){
                $this->success('删除成功！', U('proindex'));
            }else{
                $this->error("删除失败！");
            }
            
        }
    }
    
    //删除团购分级
    public function specdelajax($id = "") {
        
        IF ($id == "") {
            $this->error("团购分级刪除失败!");
        }
        $ProductspecData = array('status' => -1,'syncStatus' => 3);
        $Productspec = D('grouppurchase_grade');
        if ($Productspec->where(array('id' => $id))->save($ProductspecData)) {
            $this->success("团购分级刪除成功!");
        } else {
            $this->error("团购分级刪除失败！");
        }
    }

    //修改后保存团购分级
    public function speceditajax($id = "", $price = "", $saleCnt = "") {
        IF ($id == "" || $price == "" || $saleCnt == "" ) {
            $this->error("团购分级修改失败!");
        }
        
        
        
        $syncStatus = M('grouppurchase_grade')->where(array('id' => $id))->getField('syncStatus');
        
        if($syncStatus == 0){
            //已经上推过了
            $ProductspecData = array('price' => $price, 'saleCnt' => $saleCnt,'lastupdate'=>NOW_TIME,'syncStatus' => 2);
        }else{
            //还没上推过了
            $ProductspecData = array('price' => $price, 'saleCnt' => $saleCnt,'lastupdate'=>NOW_TIME);
        }
        
        $Productspec = D('grouppurchase_grade');
        if ($Productspec->where(array('id' => $id))->save($ProductspecData)) {
            $this->success("团购分级修改成功!");
        } else {
            $this->error("数据没有发生变化，修改失败！");
        }
    }
    
    /**
     * 订单导出
     * @author zhangwei
     * 2015-06-22
     */
    public function orderExport(){
        $Model = new Model();
        
        $id = I('id');          //订单编号
        $aid = I('aid');        //区域
        $dayId = I('dayId');    //当天订单序号
        $status = I('status');  //订单状态
        $b_date = I('b_date');  //开始时间
        $e_date = I('e_date');  //结束时间
        
        //拼接SQL语句
        $sql = "select a.orderid,a.amount,a.finalAmount,a.payway,a.payDetails,a.status,a.isExport,a.isPrint from gr_gp_order a where 1=1 ";
        
        if ($id) {
            $sql .= " and a.orderid like '%".$id."%'";
        }
        if ($dayId) {
            $sql .= " and a.serialNo = '".$dayId."'";
        }
        if ($aid) {
            $sql .= " and a.areaId = '".$aid."'";
        }
        if ($status) {
            $sql .= " and a.status = '".$status."'";
        }
        if ($b_date) {
            $sql .= " and date_format(a.createDate,'%Y-%m-%d') >= '".$b_date."' ";
        }
        if ($e_date) {
            $sql .= " and date_format(a.createDate,'%Y-%m-%d') <= '".$e_date."' ";
        }
        $sql .= " order by createDate,orderid desc";
        $data = $Model->query($sql);
        
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");

        $filename="团购订单（".$b_date."-".$e_date."）";
        
        $headArr=array("订单编号","总价","实付金额","支付方式","支付详情","状态","是否导出过","小票是否打印过");
        $title = "订单列表";
        $this->getExcel($filename,$headArr,$data,$title);
    }

    private function getExcel($fileName,$headArr,$data,$title){
         //对数据进行检验
        if(empty($data) || !is_array($data)){
            //die("data must be a array");
        }
        //检查文件名
        if(empty($fileName)){
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s",time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $title);

        
        //第二列设置报表列头
        $key = ord("A");
        foreach($headArr as $v){
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach($data as $key => $rows){ //行写入
            $span = ord("A");
            foreach($rows as $keyName=>$value){// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j.$column, $value);
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
            // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');

            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    
    /**
     * 团购活动及团购商品数据上推
     * @author wangyuanlin
     * 2015-06-23
     */
    public function push(){
       
       $reuslt = D("GroupPurchaseLeanCloud")->push();               //团购活动表
       $reuslt = D("GroupPurchaseProLeanCloud")->push();            //团购活动商品表
       $reuslt = D("GroupPurchaseGradeLeanCloud")->push();          //团购活动商品分级表
       
       $this->success('数据上推成功！', U('index'),true);
    }
    
    /**
     * 团购订单数据上推
     * @author James
     * 2015-06-30
     */
    public function orderPush() {
        //获取要上推的数据源
        $list = M('gp_order')->where(array('syncStatus'=>2))->select();
        
        //执行上推操作
        $list = $this->pushParse('GroupPurchaseOrder',
            array('objectId'=>'id',
                'sendTime'=>'sendTime',
                'remark'=>'remark',
                'areaId'=>'areaId',
                'logisticsNo'=>'logisticsNo',
                'logistics'=>'logistics',
                'status'=>'status',
                'syncStatus'=>'syncStatus'),
            function($src){
                //前调函数
                $micro = sprintf("%03d",($src['sendTime'] - floor($src['sendTime'])) * 1000);
                $src['sendTime'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['sendTime']).'T'.date('H:i:s',$src['sendTime']).'.'.$micro.'Z');
                    
                $src['status'] = intval($src['status']);
                
                return $src;
            },
            function($src){
                //后调函数
                //数据上推到云端后，更新本地数据的同步状态 （syncStatus ＝ 0）
                $m = M('gp_order');
                $m->where('id=\''.$src['objectId'].'\'')->data(array('syncStatus'=>0))->save();
                return $src;
            },
            $list);
            
        $this->success('订单数据上推成功！', U('order'), true);
    }

    /**
     * 团购订单数据下拉
     * @author James
     * 2015-06-30
     */
    public function orderPull() {
        
        $rest = new Rest();
        
        $res = $rest->getList('GroupPurchaseOrder');
        $list = $res->body->results;
        
        $list = $this->pullParse('gp_order','GroupPurchaseOrder',
            array(),
            function($src){
                //前调函数
                $src['createDate'] = strtotime($src['createDate']);
                $src['lastupdate'] = strtotime($src['lastupdate']);
                
                //修改 地址信息
                $address = (array)($src['address']);
                $src['toStreet'] = $address['address'];
                $src['toPhone'] = $address['phone'];
                $src['toName'] = $address['name'];
                $src['toCity'] = $address['city'];
                $src['toArea'] = $address['area'];
                $src['toProvince'] = $address['province'];
                
                //修改 经纬度信息
                $location = $src['location'];
                $src['toLon'] = substr($location, 0,strpos($location,','));
                $src['toLat'] = substr($location, strpos($location,',')+1);
                
                //划分区域
                $GeoUtils=new BMap\GeoUtils();
                $areaId=$GeoUtils->isPointInArea($src['toLon'],$src['toLat']);
                $src['areaId'] = $areaId;
                
                return $src;
            },
            function($src){
                //后调函数
                $goods = $src['goods'];
                $list = array();
                foreach($goods as $g){
                    $g = (array)$g;
                    $list[] = array('orderid' => $g['orderid'],
                        'pid'=>$g['sid'],'cartnum'=>$g['size'],'createdate'=>0,'lastupdate'=>0,'syncStatus'=>1);
                }
                
                $m = M('gp_order_goods');
                $flag = $m->addAll($list);
                $src['goodsFlag'] = $flag;
                
                return $src;
            },
            $list);
             
        $this->success('订单数据下拉成功！', U('order'), true);
    }
}